package netty.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.dns.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.NetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DnsTcpServer {

    // google 8.8.8.8
    // 114.114.114.114 114.114.115.115
    // ali: 223.5.5.5 223.6.6.6
    // baidu: 180.76.76.76
    // 电信：首选：101.226.4.6
    // 联通：首选：123.125.81.6
    // 移动：首选：101.226.4.6
    // 铁通：首选：101.226.4.6

    static final String DNS_SERVER_HOST = System.getProperty("host", "127.0.0.1");
    static final int DNS_SERVER_PORT = Integer.parseInt(System.getProperty("port", "853"));

    static final String QUERY_DOMAIN = "www.example.com";
    static final byte[] QUERY_RESULT = new byte[]{(byte) 192, (byte) 168, 1, 1};

    public static void main(String[] args) throws Exception {

        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss, group)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new LoggingHandler(LogLevel.INFO));

                            p.addLast(new TcpDnsQueryDecoder());
                            p.addLast(new TcpDnsResponseEncoder());
                            p.addLast(new SimpleChannelInboundHandler<DnsQuery>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, DnsQuery msg) {
                                    DnsQuestion question = msg.recordAt(DnsSection.QUESTION);
                                    log.info("Query domain: " + question);

                                    //always return 192.168.1.1
                                    ctx.writeAndFlush(newResponse(msg, question, 600L, QUERY_RESULT));
                                }

                                private DefaultDnsResponse newResponse(
                                        DnsQuery query,
                                        DnsQuestion question,
                                        long ttl, byte[]... addresses) {
                                    DefaultDnsResponse response = new DefaultDnsResponse(query.id());
                                    response.addRecord(DnsSection.QUESTION, question);

                                    for (byte[] address : addresses) {
                                        DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord(
                                                question.name(),
                                                DnsRecordType.A, ttl, Unpooled.wrappedBuffer(address));
                                        response.addRecord(DnsSection.ANSWER, queryAnswer);
                                    }
                                    return response;
                                }
                            });
                        }
                    });

            ChannelFuture f = b.bind(DNS_SERVER_PORT).sync();
            Channel ch = f.channel();

            Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        clientQuery();
                        ch.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 1000, TimeUnit.MILLISECONDS);

            // Wait until the connection is closed.
            // ch.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    private static void clientQuery() throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new TcpDnsQueryEncoder())
                                    .addLast(new TcpDnsResponseDecoder())
                                    .addLast(new SimpleChannelInboundHandler<DefaultDnsResponse>() {
                                        @Override
                                        protected void channelRead0(ChannelHandlerContext ctx, DefaultDnsResponse msg) {
                                            try {
                                                handleQueryResp(msg);
                                            } finally {
                                                ctx.close();
                                            }
                                        }
                                    });
                        }
                    });

            final Channel ch = b.connect(DNS_SERVER_HOST, DNS_SERVER_PORT).sync().channel();

            int randomID = new Random().nextInt(60000 - 1000) + 1000;
            DnsQuery query = new DefaultDnsQuery(randomID, DnsOpCode.QUERY)
                    .setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
            ch.writeAndFlush(query).sync();
            boolean success = ch.closeFuture().await(10, TimeUnit.SECONDS);
            if (!success) {
                log.error("dns query timeout!");
                ch.close().sync();
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    private static void handleQueryResp(DefaultDnsResponse msg) {
        log.info(">>> count: {}", msg.count());
        if (msg.count(DnsSection.QUESTION) > 0) {
            DnsQuestion question = msg.recordAt(DnsSection.QUESTION, 0);
            log.info(">>> name: {}", question.name());
        }
        for (int i = 0, count = msg.count(DnsSection.ANSWER); i < count; i++) {
            DnsRecord record = msg.recordAt(DnsSection.ANSWER, i);
            if (record.type() == DnsRecordType.A) {
                //just print the IP after query
                DnsRawRecord raw = (DnsRawRecord) record;
                log.info(">>> raw-dns: {}", NetUtil.bytesToIpAddress(ByteBufUtil.getBytes(raw.content())));
            }
        }
    }
}
